package android.framework.binding;

import java.util.Date;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

public class BindableTimePicker extends TimePicker implements IBindable<Date>, OnTimeChangedListener{

	private ViewBindingHandler<Date> bindingHandler = new ViewBindingHandler<Date>();
	
	public BindableTimePicker(Context context) {
		super(context);
		setOnTimeChangedListener(this);
	}
	
	public BindableTimePicker(Context context, AttributeSet attrs) {
		super(context, attrs);
		setOnTimeChangedListener(this);
	}
	
	public BindableTimePicker(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		setOnTimeChangedListener(this);
	}

	public boolean notifyChanges(Date value, long actionId) {
		boolean notifyChanges = bindingHandler.notifyChanges(value, actionId);
		if(notifyChanges && value != null){
			setCurrentHour(value.getHours());
			setCurrentMinute(value.getMinutes());
		}
		return notifyChanges;
	}

	public void addListener(IObserver<Date> listener) {
		bindingHandler.addListener(listener);
	}

	public void removeListener(IObserver<Date> listener) {
		bindingHandler.removeListener(listener);
	}

	public void setListener(MultiBindingAdapter<Date> listener) {
		bindingHandler.setListener(listener);
	}

	public void clearListeners() {
		bindingHandler.clearListeners();
	}

	public Date getLastValue() {
		return bindingHandler.getLastValue();
	}

	public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
		Date newDate = new Date();
		newDate.setHours(hourOfDay);
		newDate.setMinutes(minute);
		if(bindingHandler.lastValue == null || !bindingHandler.lastValue.equals(newDate)){
			bindingHandler.lastValue = newDate;
			bindingHandler.notifyListener(newDate);
		}	
	}

	

	

}
